#define _CRT_SECURE_NO_WARNINGS 1
#include "string.h"

namespace zj//应该与头文件的命名空间一致
{
	const size_t string::npos = -1;
	string::string(const char* str)//构造的是头文件的函数
		:_size(strlen(str))
	{
		_capacity = _size;
		_str = new char[_size + 1];
		strcpy(_str, str);
	}

	string::~string()
	{
		delete[]_str;
		_str = nullptr;
		_size = 0;
		_capacity = 0;
	}

	//动态开辟一块空间
	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* tmp = new char[n + 1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}

	void string::push_back(char ch)
	{
		if (_size + 1 > _capacity)
		{
			reserve(_capacity == 0 ? 4 : _capacity * 2);//如何等于0，直接给4，如果不等于2倍扩容。
		}
		_str[_size] = ch;
		++_size;
		_str[_size] = '\0';
	}
	void string::append(const char* str)//字符串追加
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			size_t newCapacity = 2 * _capacity;//计算新的容量
			if (_size + len > 2 * _capacity)
			{
				newCapacity = _size + len;
			}
			reserve(newCapacity);//扩容
		}
		strcpy(_str + _size, str);
		_size += len;
	}

	string& string::operator+=(char ch)//正确支持链式调用,传值
	{
		push_back(ch);
		return *this;
	}

	string& string::operator+=(const char* str)//传地址，字符串
	{
		append(str);
		return *this;
	}

	void string::insert(size_t pos, size_t n, char ch)//插入的是单个字符
		//如果要插入字符串，就要const char*,使用重载
	{
		assert(pos <= _size);
		if (_size + n > _capacity)
		{
			size_t newCapacity = 2 * _capacity;
			if (_size + n > newCapacity)
			{
				newCapacity = _size + n;
			}
			reserve(newCapacity);
		}
		size_t end = _size;
		while (end >= pos)
		{
			_str[end + n] = _str[end];
			--end;
		}
		for (size_t i = 0; i < n; i++)
		{
			_str[pos + i] = ch;
		}
		_size += n;
	}
}